/* Copyright (C) 1999-2005 by Peter Eastman

   This program is free software; you can redistribute it and/or modify it under the
   terms of the GNU General Public License as published by the Free Software
   Foundation; either version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but WITHOUT ANY 
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */

package artofillusion;

import artofillusion.math.*;
import artofillusion.object.*;
import artofillusion.ui.*;
import buoy.event.*;
import java.awt.*;

/** TaperMeshTool is an EditingTool used for tapering the vertices of TriangleMesh objects. */

public class TaperMeshTool extends EditingTool
{
  private boolean noSelection, taperAll, towardCenter;
  private Point clickPoint;
  private int whichHandle;
  private BoundingBox bounds;
  private double boundsHeight, boundsWidth;
  private Vec3 baseVertPos[];
  private UndoRecord undo;
  private MeshEditController controller;
  
  public static final int HANDLE_SIZE = 5;
  private static Image icon, selectedIcon;

  public TaperMeshTool(EditingWindow fr, MeshEditController controller)
  {
    super(fr);
    this.controller = controller;
    icon = loadImage("taperPoints.gif");
    selectedIcon = loadImage("selected/taperPoints.gif");
  }

  public void activate()
  {
    super.activate();
    int selected[] = controller.getSelectionDistance();
    noSelection = false;
    for (int i = 0; i < selected.length; i++)
      if (selected[i] == 0)
        {
          theWindow.setHelpText(Translate.text("taperMeshTool.helpText"));
          return;
        }
    theWindow.setHelpText(Translate.text("taperMeshTool.errorText"));
    noSelection = true;
  }

  public int whichClicks()
  {
    return ALL_CLICKS;
  }

  public Image getIcon()
  {
    return icon;
  }

  public Image getSelectedIcon()
  {
    return selectedIcon;
  }

  public String getToolTipText()
  {
    return Translate.text("taperMeshTool.tipText");
  }

  public void drawOverlay(Graphics g, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex v[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Rectangle b;

    if (noSelection)
      return;
    g.setColor(Color.red);
    b = findScreenBounds(findSelectionBounds(v, cam, (MeshViewer) view), cam, (MeshViewer) view);
    if (b != null)
      {
        g.fillRect(b.x, b.y, HANDLE_SIZE, HANDLE_SIZE);
        g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y, HANDLE_SIZE, HANDLE_SIZE);
        g.fillRect(b.x, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
        g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
      }
  }
  
  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex v[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Rectangle b;
    int j, k;
    
    if (noSelection)
      return;
    clickPoint = e.getPoint();
    
    // Determine which handle was clicked on.
    
    bounds = findSelectionBounds(v, cam, (MeshViewer) view);
    b = findScreenBounds(bounds, cam, (MeshViewer) view);
    if (!b.contains(clickPoint))
      {
        whichHandle = -1;
        return;
      }
    if (clickPoint.x <= b.x+HANDLE_SIZE)
      j = 0;
    else if (clickPoint.x >= b.x+b.width-HANDLE_SIZE)
      j = 1;
    else j = -1;
    if (clickPoint.y <= b.y+HANDLE_SIZE)
      k = 0;
    else if (clickPoint.y >= b.y+b.height-HANDLE_SIZE)
      k = 1;
    else k = -1;
    if (j == -1 || k == -1)
      {
        whichHandle = -1;
        return;
      }
    if (j == 0 && k == 0)
      whichHandle = 0;
    else if (j == 1 && k == 0)
      whichHandle = 1;
    else if (j == 0 && k == 1)
      whichHandle = 2;
    else if (j == 1 && k == 1)
      whichHandle = 3;
    taperAll = e.isShiftDown();
    towardCenter = e.isControlDown();
    boundsHeight = (double) b.height;
    boundsWidth = (double) b.width;
    baseVertPos = mesh.getVertexPositions();
  }
  
  public void mouseDragged(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex vert[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Point dragPoint = e.getPoint();
    Vec3 v[];
    Vec2 p;
    int i, vertSize = MeshViewer.HANDLE_SIZE;
    int selectDist[] = controller.getSelectionDistance();
    double size, xtaper, ytaper, ztaper;
    
    if (noSelection || whichHandle == -1)
      return;
    if (undo == null)
      undo = new UndoRecord(theWindow, false, UndoRecord.COPY_VERTEX_POSITIONS, new Object [] {mesh, mesh.getVertexPositions()});
    v = findTaperedPositions(baseVertPos, dragPoint, (MeshViewer) view);
    mesh.setVertexPositions(v);
    controller.objectChanged();
    theWindow.updateImage();
  }

  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex vert[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Point dragPoint = e.getPoint();
    int i;
    Vec3 v[];
    double size, xtaper, ytaper, ztaper;

    if (noSelection || whichHandle == -1)
      return;
    if (undo != null)
      theWindow.setUndoRecord(undo);
    v = findTaperedPositions(baseVertPos, e.getPoint(), (MeshViewer) view);
    mesh.setVertexPositions(v);
    controller.objectChanged();
    theWindow.updateImage();
    theWindow.setHelpText(Translate.text("taperMeshTool.helpText"));
    undo = null;
    baseVertPos = null;
  }

  /* This method returns a bounding box for the selected vertices in view coordinates. */
  
  BoundingBox findSelectionBounds(MeshVertex vert[], Camera cam, MeshViewer view)
  {
    int selected[] = controller.getSelectionDistance();
    double minx, miny, minz, maxx, maxy, maxz;
    Vec3 v;
    int i;
    
    minx = miny = minz = Double.MAX_VALUE;
    maxx = maxy = maxz = -Double.MAX_VALUE;
    for (i = 0; i < vert.length; i++)
      {
        if (selected[i] == 0)
          {
            v = cam.getObjectToView().times(vert[i].r);
            if (v.x < minx) minx = v.x;
            if (v.x > maxx) maxx = v.x;
            if (v.y < miny) miny = v.y;
            if (v.y > maxy) maxy = v.y;
            if (v.z < minz) minz = v.z;
            if (v.z > maxz) maxz = v.z;
          }
      }
    return new BoundingBox(minx, maxx, miny, maxy, minz, maxz);
  }
  
  /* Given a bounding box in view coordinates, find the corresponding rectangle in
     screen coordinates. */
  
  Rectangle findScreenBounds(BoundingBox b, Camera cam, MeshViewer view)
  {
    CoordinateSystem coords = controller.getObject().coords;
    Mat4 m = cam.getObjectToWorld();
    Rectangle r;
    
    cam.setObjectTransform(cam.getViewToWorld());
    r = cam.findScreenBounds(b);
    cam.setObjectTransform(m);
    if (r != null)
      r.setBounds(r.x-10, r.y-10, r.width+20, r.height+20);
    return r;
  }

  /* Find the new positions of the vertices after scaling. */

  Vec3 [] findTaperedPositions(Vec3 vert[], Point pos, MeshViewer view)
  {
    Vec3 v[] = new Vec3 [vert.length];
    int selected[] = controller.getSelectionDistance();
    Camera cam = view.getCamera();
    double clickX, clickY, posX, posY, taper;
    Vec3 center;
    Mat4 m1, m2;
    int i, direction;
    
    clickX = (double) clickPoint.x;
    clickY = (double) clickPoint.y;
    posX = (double) pos.x;
    posY = (double) pos.y;
    
    // Figure out which way to taper the mesh, and toward which point.
    
    direction = (Math.abs(posX-clickX) > Math.abs(posY-clickY)) ? 0 : 1;
    center = new Vec3(0.0, 0.0, (bounds.minz+bounds.maxz)/2.0);
    if (bounds.minx == bounds.maxx || bounds.miny == bounds.maxy)
      taper = 0.0;
    else if (direction == 0)
      {
        if (towardCenter)
          center.x = (bounds.minx+bounds.maxx)/2.0;
        else if (whichHandle == 0 || whichHandle == 2)
          center.x = bounds.minx;
        else
          center.x = bounds.maxx;
        if (whichHandle == 0 || whichHandle == 1)
          center.y = bounds.miny;
        else
          center.y = bounds.maxy;
        if (whichHandle == 0 || whichHandle == 2)
          taper = (posX-clickX)/boundsWidth;
        else
          taper = (clickX-posX)/boundsWidth;
        if (taper > 1.0)
          taper = 1.0;
        if (whichHandle == 2 || whichHandle == 3)
          taper *= -1.0;
      }
    else
      {
        if (towardCenter)
          center.y = (bounds.miny+bounds.maxy)/2.0;
        else if (whichHandle == 0 || whichHandle == 1)
          center.y = bounds.miny;
        else
          center.y = bounds.maxy;
        if (whichHandle == 0 || whichHandle == 2)
          center.x = bounds.minx;
        else
          center.x = bounds.maxx;
        if (whichHandle == 0 || whichHandle == 1)
          taper = (posY-clickY)/boundsWidth;
        else
          taper = (clickY-posY)/boundsWidth;
        if (taper > 1.0)
          taper = 1.0;
        if (whichHandle == 1 || whichHandle == 3)
          taper *= -1.0;
      }

    // If the points are not being tapered, just copy them over.
    
    if (taper == 0.0)
      {
        for (i = 0; i < vert.length; i++)
          v[i] = new Vec3(vert[i]);
        return v;
      }

    // Find the transformation matrix.
    
    m1 = cam.getObjectToView();
    m1 = Mat4.translation(-center.x, -center.y, -center.z).times(m1);
    m2 = Mat4.translation(center.x, center.y, center.z);
    m2 = cam.getViewToWorld().times(m2);
    m2 = view.getDisplayCoordinates().toLocal().times(m2);
    
    // Determine the deltas.
    
    for (i = 0; i < vert.length; i++)
      {
        if (selected[i] == 0)
          {
            v[i] = m1.times(vert[i]);
            if (direction == 0)
              {
                v[i].x *= 1.0 - taper*v[i].y/(bounds.maxy-bounds.miny);
                if (taperAll)
                  v[i].z *= 1.0 - taper*v[i].y/(bounds.maxy-bounds.miny);
              }
            else
              {
                v[i].y *= 1.0 - taper*v[i].x/(bounds.maxx-bounds.minx);
                if (taperAll)
                  v[i].z *= 1.0 - taper*v[i].x/(bounds.maxx-bounds.minx);
              }
            v[i] = m2.times(v[i]).minus(vert[i]);
          }
        else
          v[i] = new Vec3();
      }
    if (theFrame instanceof MeshEditorWindow)
      ((MeshEditorWindow) theFrame).adjustDeltas(v);
    for (i = 0; i < vert.length; i++)
      v[i].add(vert[i]);
    return v;
  }
}